﻿Imports System.ComponentModel.Composition
Imports System.ComponentModel
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Threading
Imports System.Net
Imports System.Net.Sockets
Imports System.Windows.Media
Imports System.Windows.Threading
Imports System.Web
Imports Pronama.Misao

<AddInExport("{531c91d8-d469-495c-83bc-dfc128594b36}", "Realtime Tweet",
    Description:="Get realtime tweets",
    HasSetting:=True,
    IconUri:="/AddIn.RealtimeTweet;component/Icon.png")>
<Export(GetType(ISourceAddIn))>
Public Class RealtimeTweetSource
    Implements ISourceAddIn

    Private Activated As Boolean
    Private Client As TwitterClient

    Private UserName As String
    Private Password As String
    Private SearchWord As String
    Private RemoveHashtags As Boolean

    Private Sub Start()

        If Not IsValid() Then
            WriteLog.Invoke(Me, New Log With {.Text = "Error: Invalid setting"})
            Deactivate()
            Exit Sub
        End If

        Activated = True

        Dim Worker = New Thread(
            Sub()
                Try
                    Client = New TwitterClient()
                    Client.SearchWord = SearchWord
                    AddHandler Client.MessageReceived, Sub(sender As Object, e As MessageReceiveEventArgs)
                                                           Me.PostMessage.Invoke(Me, New Message() With {
                                                                                   .Text = RemoveLastHashtags(e.Tweet.Text),
                                                                                   .Size = MessageSize.Small,
                                                                                   .Motion = MessageMotion.FlowDown,
                                                                                   .ForegroundColor = Colors.White
                                                                                   })
                                                       End Sub
                    Client.Connect(UserName, Password)

                Catch ex As Exception
                    WriteLog.Invoke(Me, New Log With {.Text = "Error: " & ex.Message})
                    Close()
                End Try
            End Sub
        )
        Worker.Start()

    End Sub

    Private Function IsValid() As Boolean

        If UserName <> "" AndAlso Password <> "" Then

            If SearchWord = "" Then
                SearchWord = "twitter"
            End If

            Return True
        End If

        Return False

    End Function

    Private Sub Close()

        If Not Client Is Nothing Then
            Client.Close()
        End If

        Activated = False
        OnDeactivated(EventArgs.Empty)

    End Sub

    Private Function RemoveLastHashtags(ByVal text As String) As String

        If Not Me.RemoveHashtags Then
            Return text
        End If

        Return Regex.Replace(text, "\s*(#\w+[\s\r]*)*$", "")

    End Function

#Region "ISourceAddIn"

    Public Sub Activate() Implements IAddIn.Activate

        If Not Activated Then
            Me.Start()
        End If

    End Sub

    Public Sub Deactivate() Implements IAddIn.Deactivate

        If Activated Then
            Me.Close()
        End If

    End Sub

    Public Event Deactivated(ByVal sender As Object, ByVal e As System.EventArgs) Implements IAddIn.Deactivated

    Protected Sub OnDeactivated(ByVal e As EventArgs)
        RaiseEvent Deactivated(Me, e)
    End Sub

    Public Sub ShowDialog(ByVal owner As System.Windows.Window) Implements IAddIn.ShowDialog

        'ToDo Create setting model.

        Dim window = New SettingWindow
        window.UserTextBox.Text = Me.UserName
        window.PassTextBox.Password = Me.Password
        window.SearchWordTextBox.Text = Me.SearchWord
        window.RemoveHashtags.IsChecked = Me.RemoveHashtags
        window.Owner = owner
        window.WindowStartupLocation = Windows.WindowStartupLocation.CenterOwner

        If window.ShowDialog Then
            Me.UserName = window.UserTextBox.Text.Trim
            Me.Password = window.PassTextBox.Password.Trim
            Me.SearchWord = window.SearchWordTextBox.Text.Trim
            Me.RemoveHashtags = window.RemoveHashtags.IsChecked
        End If

    End Sub

    <Import(GetType(PostMessageCallback))>
    Property PostMessage As PostMessageCallback Implements ISourceAddIn.PostMessage

    <Import(GetType(WriteLogCallback))>
    Public Property WriteLog As WriteLogCallback Implements ISourceAddIn.WriteLog

#End Region

End Class
